/**
 * Description: UDP 服务端
 * File: udp_server.c |Time: 2021-04-12 13:48
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define BUF_SIZE 100
#define ERR(msg) do {   \
    perror(msg);        \
    printf("[err]%s:%s:%d\n", __FILE__, __func__, __LINE__); \
    exit(EXIT_FAILURE); \
} while(0)

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s <ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == sockfd) {
        ERR("socket");
    }
    char buff[BUF_SIZE] = {0};

    struct sockaddr_in serveraddr;

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (-1 == bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)))
    {
        ERR("bind");
    }

    while(1) {
        // UDP 服务端只能recv接收请求， 无法发送到客户端
        // 因为不知道客户端目的地址
        if (-1 == recv(sockfd, buff, sizeof(buff), 0))
        {
            ERR("recv");
        }
        printf("[from_client] %s\n", buff);
    }


    return 0;
}
